




import paramiko
import os
from configparser  import ConfigParser





class myParamiko:
    def __init__(self,config_str,session):
        self.config = ConfigParser()
        self.config.read(config_str)
        self.hostip = self.config.get(session,'host')
        self.port = self.config.get(session,'port')
        self.username = self.config.get(session,'username')
        self.password = self.config.get(session,'password')
        self.obj = paramiko.SSHClient()
        self.obj.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.obj.connect(self.hostip,self.port,self.username,self.password)
        self.objsftp = self.obj.open_sftp()

    def run_cmd(self,cmd):
        stdin,stdout,stderr = self.obj.exec_command(cmd)
        return stdout.read()

    def run_cmdlist(self,cmdlist):
        self.resultList = []
        for cmd in cmdlist:
            stdin,stdout,stderr = self.obj.exec_command(cmd)
            self.resultList.append(stdout.read())
        return self.resultList

    def get(self,remotepath,localpath,file):
        self.objsftp.get(remotepath+file,localpath+file)

    def put(self,localpath,remotepath,file):
        self.objsftp.put(localpath+file,remotepath+file)

    def getTarPackage(self,path):
        list = self.objsftp.listdir(path)
        for packageName in list:
            stdin,stdout,stderr  = self.obj.exec_command("cd " + path +";"
                                                         + "tar -zvcf /tmp/" + packageName
                                                         + ".tar.gz " + packageName)
            stdout.read()
            self.objsftp.get("/tmp/" + packageName + ".tar.gz","D:\\1\\" + packageName + ".tar.gz")
            self.objsftp.remove("/tmp/" + packageName + ".tar.gz")
            print ("get package from " + packageName + " ok......")

    def close(self):
        self.objsftp.close()
        self.obj.close()

def upload_a_file():
    sshobj = myParamiko('config.ini','ssh0')
    apath = '/home/zhouqi/Desktop/'
    bpath = 'D:\\2\\'
    file = 'tomcat-trunk.zip'
    # sshobj.get(apath,bpath,file)

    for (root, dirs, files) in os.walk(bpath):
        for filename in files:
            file = str(filename)
            sshobj.put(bpath, apath, file)

    sshobj.close()

if __name__ == '__main__':
    sshobj = myParamiko('config.ini','ssh0')
    apath = '/tmp/'
    sshobj.getTarPackage(apath)

